import { rpc } from '../odoojs/index.js'
import { login } from './login.js'

// const model_name = 'res.partner'
// const fields = {
//   name: {},
//   email: {},
//   bank_ids: { fields: ['bank_bic', 'bank_id'] }
// }

// const model_name = 'res.bank'
// const fields = {
//   name: {},
//   email: {}
// }

const model_name = 'res.partner.category'
const fields = {
  name: {},
  color: {}
}

let editmodel = null

const state = {
  editable: false,
  fields: {},
  record_only: {},
  record_display: {},
  values: {}
}

async function init() {
  const Model = rpc.env.model(model_name)
  const metadata = await Model.load_metadata({ fields })
  editmodel = rpc.env.editmodel(model_name, { metadata })
  state.fields = editmodel.get_fields_all(fields)
  const res = await editmodel.onchange()
  const { record_display, domain, values } = res
  state.record_display = { ...record_display }
  state.values = { ...values }
  state.fields = editmodel.get_fields_all(fields)
  state.editable = true

  console.log('state', state)
}

async function onChange(fname, value) {
  const result = await editmodel.onchange(fname, value)
  const { record_display, values, domain } = result
  state.record_display = { ...record_display }
  state.values = { ...values }
  state.fields = editmodel.get_fields_all(fields)
  console.log('state', state)
}

async function handelCommit() {
  const id_ret = await editmodel.commit((done) => {
    done(true)
  })

  console.log('id_ret', id_ret)
  const Model = rpc.env.model(model_name)
  const res = await Model.load_data_one(id_ret, { fields })
  console.log('new ok', res)
}

async function test() {
  await login()
  await init()
  await onChange('name', 'TAG-' + Math.random())
  await onChange('color', 2)
  await handelCommit()
}

test()
